"""
初始化数据，如果没有缓存就从wind读取，如果有缓存从缓存读取
"""
import pickle
import os
import datetime
import pandas as pd


def get_data(update: bool = False, path="美国通胀.xlsx") -> dict:
    full_path = f"./input/{path}"
    cache_path = full_path.replace('xlsx', 'pkl')
    if update:
        df = pd.read_excel(full_path)
        re_dic = {}
        for _, se in df.iterrows():
            data_dic = get_data_from_edb(se['指标ID'], se['指标名称'])
            re_dic[se['指标名称']] = {**data_dic, **se.to_dict()}
        save_pickle(re_dic, cache_path)
    else:
        if not os.path.exists(cache_path):
            re_dic = get_data(True, path)
        else:
            re_dic = pd.read_pickle(cache_path)
    return re_dic


def get_data_from_edb(id_: str, name: str) -> dict:
    from WindPy import w  # 放在外面有些人可能没有windpy导致import出现问题
    print(id_, name)
    if not w.isconnected():
        w.start()
    today = datetime.datetime.today().__str__()[:10]
    resp = w.edb(id_, beginTime='2000-01-01', endTime=today)
    print(resp.ErrorCode)
    temp_dic = {
        '__id': id_,
        'df': pd.DataFrame(resp.Data, columns=[pd.to_datetime(str(s)) for s in resp.Times], index=[name]).T,
        'name': name}
    return temp_dic


def save_pickle(save_data, path: str) -> str:
    with open(path, 'wb') as fo:
        pickle.dump(save_data, fo)
    return path


if __name__ == "__main__":
    data = get_data(update=False, path="美国通胀数据.xlsx")
